<template>
  <div>
    <!-- 头部 -->
    <el-row>
      <el-col :span="12">
        <div class="title">工程信息：</div>
      </el-col>
      <el-col :span="12">
        <div class="my_button">
          <!-- 添加展开按钮，点击时触发 toggleShowAll 函数 -->
          <el-popover placement="top" width="160" v-model="visibleSuccess"
          ><p>确定上传吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visibleSuccess = false"
              >取消</el-button
              >
              <el-button type="primary" size="mini" @click="uploadSuccess"
              >确定</el-button
              >
            </div>
            <el-button
              type="success"
              size="small"
              icon="el-icon-check"
              slot="reference"
              :disabled="disabled"
              v-show="canUpload(engList)"
            >上传</el-button
            >
          </el-popover>

          <el-button type="success" size="small" icon="el-icon-sort"
                     @click="toggleShowAll" :disabled="disabled">{{ showAll ? "收起" : "展开" }}
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-edit"
                     @click="editing" :disabled="disabled">编辑
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 工程信息表单 -->
    <template v-if="eng && Object.keys(eng).length > 0">
      <el-form :label-position="'right'" label-width="160px" :model="engList">
        <el-row :gutter="10" style="margin-top: 20px">
          <template v-for="comment in visibleCommentList">
            <el-col
              :key="comment.columnname"
              :span="12"
              class="form-col"
              v-if="comment.columncomment !== ''"
            >
              <el-form-item :label="comment.columncomment + '：'">
                <div class="table-content">
                  {{ engList[comment.columnname] }}
                </div>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
    </template>
    <template v-else>
      <el-empty description="无工程信息"></el-empty>
    </template>

    <!-- 编辑弹窗 -->
    <el-dialog title="工程信息编辑：" :visible.sync="dialogVisible" width="70%" center>
      <div class="dialog-content">
        <!--  <el-form size="small" :inline="true" label-width="68px" :model="tempEngList">
           <el-form-item label="数字化单位" prop="shuzihuadanwei">
             <el-input v-model="tempEngList.shuzihuadanwei" placeholder="请输入数字化单位" clearable/>
           </el-form-item>
           <el-form-item label="移交单位" prop="yijiaodanwei">
             <el-input v-model="tempEngList.yijiaodanwei" placeholder="请输入移交单位" clearable/>
           </el-form-item>
           <el-form-item label="工程地点" prop="allname">
             <el-input v-model="tempEngList.allname" placeholder="请输入工程地点" clearable/>
           </el-form-item>
           <el-form-item label="建设单位" prop="buildingorg">
             <el-input v-model="tempEngList.buildingorg" placeholder="请输入建设单位" clearable/>
           </el-form-item>
           <el-form-item label="立项批准单位" prop="checkorg">
             <el-input v-model="tempEngList.checkorg" placeholder="请输入立项批准单位" clearable/>
           </el-form-item>
           <el-form-item label="设计单位" prop="designorg">
             <el-input v-model="tempEngList.designorg" placeholder="请输入设计单位" clearable/>
           </el-form-item>
           <el-form-item label="施工单位" prop="operationorg">
             <el-input v-model="tempEngList.operationorg" placeholder="请输入施工单位" clearable/>
           </el-form-item>
           <el-form-item label="勘察单位" prop="explorationorg">
             <el-input v-model="tempEngList.explorationorg" placeholder="请输入勘察单位" clearable/>
           </el-form-item>
           <el-form-item label="监理单位" prop="supervisionorg">
             <el-input v-model="tempEngList.supervisionorg" placeholder="请输入监理单位" clearable/>
           </el-form-item>
           <el-form-item label="立项批准文号" prop="checkIssueno">
             <el-input v-model="tempEngList.checkIssueno" placeholder="请输入立项批准文号" clearable/>
           </el-form-item>
           <el-form-item label="规划许可证号" prop="planlicenseno">
             <el-input v-model="tempEngList.planlicenseno" placeholder="请输入规划许可证号" clearable/>
           </el-form-item>
           <el-form-item label="用地规划许可证号" prop="landplanlicenseno">
             <el-input v-model="tempEngList.landplanlicenseno" placeholder="请输入用地规划许可证号" clearable/>
           </el-form-item>
           <el-form-item label="施工许可证号" prop="operationlicenseno">
             <el-input v-model="tempEngList.operationlicenseno" placeholder="请输入施工许可证号" clearable/>
           </el-form-item>
           <el-form-item label="开工时间" prop="startdate">
             <el-date-picker clearable v-model="tempEngList.startdate" type="date" value-format="yyyy-MM-dd"
                             placeholder="请选择开工时间"/>
           </el-form-item>
           <el-form-item label="竣工时间" prop="enddate">
             <el-date-picker clearable v-model="tempEngList.enddate" type="date" value-format="yyyy-MM-dd"
                             placeholder="请选择竣工时间"/>
           </el-form-item>
           <el-form-item label="项目经理" prop="projmanager">
             <el-input v-model="tempEngList.projmanager" placeholder="请输入项目经理" clearable/>
           </el-form-item>
           <el-form-item label="分部(项)工程" prop="partproj">
             <el-input v-model="tempEngList.partproj" placeholder="请输入分部(项)工程" clearable/>
           </el-form-item>
           <el-form-item label="合同号" prop="cnum">
             <el-input v-model="tempEngList.cnum" placeholder="请输入合同号" clearable/>
           </el-form-item>
           <el-form-item label="申请时间" prop="applydate">
             <el-date-picker clearable v-model="tempEngList.applydate" type="date" value-format="yyyy-MM-dd"
                             placeholder="请选择申请时间"/>
           </el-form-item>
           <el-form-item label="批准时间" prop="passdate">
             <el-date-picker clearable v-model="tempEngList.passdate" type="date" value-format="yyyy-MM-dd"
                             placeholder="请选择批准时间"/>
           </el-form-item>
         </el-form>   -->

        <el-form :model="tempEngList">
          <el-row>
            <template v-for="comment in tempCommentList">
              <el-col :key="comment.columnname" :span="12" v-if="comment.columncomment !== ''">
                <el-form-item :label="comment.columncomment + '：'">
                  <el-input class="custom-input" v-model="tempEngList[comment.columnname]"/>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogData">恢复</el-button>
        <el-button type="primary" @click="saveDialogData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getEngCommentInfo, updateEng} from "@/api/system/eng";
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  // components: {Treeselect},
  props: {
    eng: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      disabled: true,
      engList: {},
      showAll: false, // 是否显示全部工程信息
      visibleCommentList: {}, // 可见的工程字段
      visibleSuccess: false,
      // 默认可见的工程字段
      defaultCommentList: ['工程名称，数字化部输入', '工程编号,数字化部输入,电子档案接收室提供格式：2016-108', '移交单位', '开工日期', '竣工日期', '案卷数',
        '工程地址', '立项批准单位', '建设单位', '设计单位', '勘察单位',
         '立项批准文号', '用地规划许可证号', '规划许可证号', '施工许可证号'],
      tempEngList: {}, // 编辑弹窗中临时保存的数据
      tempCommentList: {}, // 编辑弹窗中可编辑字段
      engCommentList: null, //工程字段信息和注释
      isEditing: false, // 是否处于编辑状态
      dialogVisible: false, // 编辑弹窗是否可见
      classOptions: [], // 类别树选项
      // // 指定属性非折叠可见
      // eng: ['id', 'engname', 'engno', 'danganguanno', 'yijiaodanwei', 'bianzhidatestart', 'bianzhidateend', 'allname',
      //   'anjuanshu', 'danganguanname', 'shuzihuadanwei', 'buildingorg', 'operationorg', 'checkorg', 'designorg',
      //   'explorationorg', 'supervisionorg', 'checkIssueno', 'planlicenseno', 'landplanlicenseno', 'landlicenseno',
      //   'operationlicenseno', 'startstation', 'endstation', 'totallength', 'projmanager']
    };
  },
  watch: {
    eng: {
      immediate: true, // 在组件创建时立即执行一次
      handler(newVal) {
        this.engList = {...newVal}; // 使用对象的深拷贝方式赋值
        this.tempEngList = {...newVal}; // 初始化编辑弹窗中的临时数据
        this.disabled = !(this.eng && Object.keys(this.eng).length > 0);
      },
    },
  },
  created() {
    this.getEngComment().then(() => {
      this.transferComment();
      // this.getTreeselect();
    });
  },
  methods: {
    // getTreeselect() {
    //   otherListClass().then(response => {
    //     this.classOptions = [];
    //     const data = { classId: 0, className: '档案分类', children: [] };
    //     data.children = this.handleTree(response.data, "classId", "parentId");
    //     this.classOptions.push(data);
    //     console.log(this.classOptions)
    //   });
    // },
    /** 转换类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.classId,
        label: node.className,
        children: node.children
      };
    },
    //转换可见的属性
    transferComment() {
      if (this.showAll) {
        this.visibleCommentList = this.engCommentList.filter(
          (comment) => comment.columncomment !== ""
        );
      } else {
        const nonEmptyComments = this.engCommentList.filter(
          (comment) => comment.columncomment !== ""
        );
        this.visibleCommentList = [];
        for (let i = 0; i < nonEmptyComments.length; i++) {
          if (this.defaultCommentList.includes(nonEmptyComments[i].columncomment)) {
            this.visibleCommentList.push(nonEmptyComments[i]);
          }
        }
      }
    },
    //转换可见的属性
    // transferComment() {
    //   this.visibleCommentList = [];
    //   if (this.showAll) {
    //     this.visibleCommentList = this.engCommentList.filter(
    //       (comment) => comment.columncomment !== ""
    //     );
    //   } else {
    //     const nonEmptyComments = this.engCommentList.filter(
    //       (comment) => comment.columncomment !== ""
    //     );
    //     this.visibleCommentList = [];
    //     // 遍历所有字段注释
    //     for (const comment of nonEmptyComments) {
    //       // 检查字段是否在eng列表中
    //       if (this.eng.includes(comment.columnname)) {
    //         // 如果在，添加到已显示的字段列表
    //         this.visibleCommentList.push(comment);
    //       }
    //     }
    //     // for (let i = 0; i < 10; i++) {
    //     //   if (nonEmptyComments[i]) {
    //     //     this.visibleCommentList.push(nonEmptyComments[i]);
    //     //   } else {
    //     //     this.visibleCommentList.push({});
    //     //   }
    //     // }
    //   }
    // },
    // 切换展开按钮的状态，显示全部工程信息或部分工程信息
    toggleShowAll() {
      this.showAll = !this.showAll;
      this.transferComment();
    },
    // 下划线转驼峰命名
    underscoreToCamel(str) {
      return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
    },
    //获取工程字段信息和注释
    getEngComment() {
      return getEngCommentInfo()
        .then((res) => {
          console.log(res);
          // this.engCommentList = res;
          this.engCommentList = res.map(comment => ({
            columncomment: comment.columncomment,
            columnname: this.underscoreToCamel(comment.columnname), // 转换属性名
          }));
        })
        .catch((error) => {
          this.$message.error("获取工程信息注释失败：" + error);
        });
    },
    editing() {
      const nonEmptyComments = this.engCommentList.filter((comment) => comment.columncomment !== "");
      this.tempCommentList = [];
      for (let i = 0; i < nonEmptyComments.length; i++) {
        if (this.defaultCommentList.includes(nonEmptyComments[i].columncomment)) {
          this.tempCommentList.push(nonEmptyComments[i]);
        }
      }
      this.isEditing = true;
      this.dialogVisible = true;
    },
    resetDialogData() {
      this.tempEngList = {...this.engList};
    },
    saveDialogData() {
      this.$confirm("确认修改吗？", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.isEditing = false;
          // 调用 updateEng 方法，并传入 tempEngList 数据
          updateEng(this.tempEngList)
            .then(() => {
              this.$message.success("保存成功！");
              // 如果保存成功，将 tempEngList 的数据同步到 engList
              this.$emit("updateEng");
              this.engList = {...this.tempEngList};
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.$message.error("保存失败：" + error);
              this.dialogVisible = false;
            });
        })
        .catch(() => {
          // 取消保存
          this.$message.info("已取消保存");
        });
    },
    uploadSuccess() {
      this.engList.yuLiuB = 1;
      this.visibleSuccess = false;
      updateEng(this.engList)
        .then(() => {
          this.$message.success("上传成功！");
          // 更新界面显示状态
          this.$emit("updateEngInfo");
        })
        .catch((error) => {
          this.$message.error("上传通过失败：" + error);
        });
    },
    canUpload(engList) {
      return engList.yuLiuB === 0 || engList.yuLiuB === -1;
    },
  },
};
</script>

<style>
.title {
  text-align: left;
  font-size: 20px;
  font-weight: bold;
  color: rgb(26, 115, 198);
  white-space: nowrap; /* 让文字不换行，保持在一行内显示 */
}

.my_button {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  margin-left: 85%;
}

.my_button button {
  margin-left: 10px; /* 增加左边距 */
  margin-right: 10px; /* 增加右边距 */
}

.dialog-content {
  max-height: 500px; /* 设置最大高度，内容区域超出时会出现滚动条 */
  overflow-y: auto; /* 内容区域出现滚动条 */
}

.dialog-footer {
  position: sticky;
  bottom: 0;
  padding: 10px;
}

.custom-input {
  width: 98%; /* 设置输入框的宽度，根据实际情况调整 */
}
</style>

